package com.xiaojian.blog.service.impl;

import com.xiaojian.blog.dao.OptionPOMapper;
import com.xiaojian.blog.exception.TipException;
import com.xiaojian.blog.model.OptionPO;
import com.xiaojian.blog.model.OptionPOExample;
import com.xiaojian.blog.service.OptionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * options表的service
 */
@Service
public class OptionServiceImpl implements OptionService {

    private static final Logger LOGGER = LoggerFactory.getLogger(OptionServiceImpl.class);

    @Resource
    private OptionPOMapper optionPOMapper;

    @Override
    @Transactional
    public void insertOption(OptionPO optionPO) {
        LOGGER.debug("Enter insertOption method:optionPO={}", optionPO);
        int i = optionPOMapper.insertSelective(optionPO);
        if (i != 1) {
            throw new TipException("inser option error");
        }
        LOGGER.debug("Exit insertOption method.");
    }

    @Override//保存方法
    @Transactional
    public void insertOption(String name, String value) {
        LOGGER.debug("Enter insertOption method:name={}, value={}", name, value);
        OptionPO optionPO = new OptionPO();
        optionPO.setName(name);
        optionPO.setValue(value);
        if (optionPOMapper.selectByPrimaryKey(name) == null) {
            optionPOMapper.insertSelective(optionPO);
        } else {
            optionPOMapper.updateByPrimaryKeySelective(optionPO);
        }
        LOGGER.debug("Exit isnertOption method");
    }

    @Override
    public List<OptionPO> getOptions() {
        return optionPOMapper.selectByExample(new OptionPOExample());
    }

    @Override
    @Transactional
    public void saveOptions(Map<String, String> options) {
        if (null != options && !options.isEmpty()) {
            options.forEach(this :: insertOption);
        }
    }

    @Override
    public OptionPO getOptionByName(String name) {
        return optionPOMapper.selectByPrimaryKey(name);
    }
}
